package cn.yunhe.action;

import com.opensymphony.xwork2.ActionSupport;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;

import java.io.*;

public class UploadsAction extends ActionSupport {
    @Setter
    @Getter
    private File[] uploads;
    @Setter
    @Getter
    private String[] uploadsContentType;
    @Setter
    @Getter
    private String[] uploadsFileName;
    @Setter
    private String savePath;

    @Override
    public String execute() throws Exception {
    for(int i=0;i<uploads.length;i++){
      String uploadPath=  getSavePath()+"\\"+uploadsFileName[i];
      doUpload(uploads[i],uploadPath);
  }
        return SUCCESS;
    }

    private void doUpload(File file,String uploadPath){
        try {
            FileOutputStream fos=new FileOutputStream(uploadPath);
            FileInputStream fis=new FileInputStream(file);
            byte [] bytes=new byte[1024];
            int len=0;
            while ((len=fis.read(bytes))!=-1){
                fos.write(bytes,0,len);
            }

            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String getSavePath() {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }
}
